<template>
  <headd />
  <div class="detail-container">
    <div class="container mx-auto px-4 py-8">
      <!-- 返回按钮 -->
      <button @click="$router.back()"
        class="group mb-8 flex items-center text-orange-600 hover:text-orange-800 transition-colors duration-300">
        <svg xmlns="http://www.w3.org/2000/svg"
          class="h-5 w-5 mr-2 transform transition-transform group-hover:-translate-x-1" fill="none" viewBox="0 0 24 24"
          stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
        </svg>
        返回列表
      </button>

      <div v-if="dog" class="max-w-4xl mx-auto">
        <!-- 主要内容卡片 -->
        <div class="bg-white rounded-2xl shadow-lg overflow-hidden border border-orange-200">
          <!-- 主图片 -->
          <div class="relative h-[500px]">
            <img :src="dog.picture" :alt="dog.title" class="w-full h-full object-cover">
            <!-- 渐变遮罩 -->
            <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/30 to-transparent"></div>

            <!-- 标题和阅读次数 -->
            <div class="absolute bottom-6 left-8 right-8 flex justify-between items-end">
              <h1 class="text-4xl font-bold text-white">{{ dog.title }}</h1>
              <div class="flex space-x-3">
                <div class="flex items-center text-white">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                    <circle cx="12" cy="12" r="3"></circle>
                  </svg>
                  {{ dog.readed }}
                </div>
              </div>
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="p-8">
            <!-- 性格标签 -->
            <div class="flex flex-wrap gap-2 mb-8">
              <span v-for="(tag, index) in dog.personalityTags" :key="index"
                class="px-4 py-2 rounded-full text-sm font-medium transition-all duration-300"
                :class="getTagStyle(index)">
                {{ tag }}
              </span>
            </div>
            <div class="prose max-w-none mb-8">
              <h2 class="text-2xl font-bold text-orange-800 mb-4">关于 {{ dog.title }}</h2>
              <p class="text-orange-600 leading-relaxed">{{ dog.content }}</p>
            </div>
          </div>
        </div>

        <!-- 额外信息卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mt-8">
          <!-- 领养须知 -->
          <div
            class="bg-white rounded-xl shadow-lg p-6 transform hover:scale-[1.02] transition-all duration-300 border border-orange-200">
            <h3 class="text-xl font-bold text-orange-800 mb-6 flex items-center">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-orange-600 mr-2" fill="none"
                viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              领养须知
            </h3>
            <ul class="space-y-4">
              <li v-for="(requirement, index) in adoptionRequirements" :key="index"
                class="flex items-start animate-fade-in" :style="{ animationDelay: `${index * 100}ms` }">
                <svg class="h-6 w-6 text-orange-600 mr-2 flex-shrink-0" fill="none" stroke="currentColor"
                  viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
                <div>
                  <h4 class="font-medium text-orange-900">{{ requirement.title }}</h4>
                  <p class="text-orange-600 text-sm">{{ requirement.description }}</p>
                </div>
              </li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div
            class="bg-white rounded-xl shadow-lg p-6 transform hover:scale-[1.02] transition-all duration-300 border border-orange-200">
            <h3 class="text-xl font-bold text-orange-800 mb-6 flex items-center">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-orange-600 mr-2" fill="none"
                viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
              </svg>
              联系方式
            </h3>
            <div class="space-y-4">
              <a v-for="(contact, index) in contactInfo" :key="index" :href="contact.link"
                class="flex items-center p-3 rounded-lg hover:bg-orange-50 transition-colors duration-300">
                <component :is="contact.icon" class="h-5 w-5 text-orange-600 mr-3" />
                <div>
                  <div class="font-medium text-orange-900">{{ contact.label }}</div>
                  <div class="text-sm text-orange-600">{{ contact.value }}</div>
                </div>
              </a>
            </div>
          </div>
        </div>

        <!-- 优化后的评论区 -->
        <div class="mt-12 bg-white rounded-xl shadow-lg p-6 border border-orange-200">
          <h2 class="text-2xl font-bold text-orange-800 mb-6">爱心留言</h2>

          <!-- 评论输入框 -->
          <div class="mb-8">
            <div class="relative">
              <textarea v-model="newComment" rows="3"
                class="w-full px-4 py-3 rounded-lg border border-orange-300 focus:border-orange-600 focus:ring focus:ring-orange-500 focus:ring-opacity-50 transition-colors resize-none bg-orange-50"
                placeholder="写下你的爱心留言..."></textarea>
              <button @click="submitComment"
                class="absolute bottom-3 right-3 px-4 py-1.5 bg-gradient-to-r from-orange-600 to-orange-700 text-white rounded-full hover:from-orange-700 hover:to-orange-800 transition-colors duration-300 text-sm"
                :disabled="!newComment.trim()">
                发表
              </button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="space-y-6">
            <div v-for="comment in comments" :key="comment.id"
              class="group bg-orange-50 rounded-lg p-4 hover:bg-orange-100 transition-all duration-300">
              <div class="flex justify-between items-start mb-2">
                <div class="flex items-center">
                  <img :src="comment.cuserAvatar" alt="Avatar" class="h-10 w-10 rounded-full mr-3">
                  <span class="font-medium text-orange-900">{{ comment.cuserName }}</span>
                  <span class="mx-2 text-orange-300">•</span>
                  <span class="text-sm text-orange-500">{{ comment.ctime }}</span>
                </div>
                <div
                  class="flex items-center space-x-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                  <button @click="likeComment(comment)"
                    class="flex items-center text-orange-500 hover:text-orange-700 transition-colors duration-300">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5"
                      :class="comment.isLiked ? 'text-orange-700 fill-current' : ''" fill="none" viewBox="0 0 24 24"
                      stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                    </svg>
                    <span class="ml-1 text-sm">{{ comment.likes }}</span>
                  </button>
                  <button @click="replyToComment(comment)"
                    class="text-orange-500 hover:text-orange-700 transition-colors duration-300">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24"
                      stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                    </svg>
                  </button>
                </div>
              </div>
              <p class="text-orange-600">{{ comment.comment }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 未找到数据时显示 -->
      <div v-else class="max-w-md mx-auto bg-white rounded-xl shadow-lg p-8 text-center border border-orange-200">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-orange-400 mx-auto mb-4" fill="none"
          viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <h1 class="text-2xl font-bold text-orange-800 mb-2">未找到该动物</h1>
        <p class="text-orange-600 mb-6">抱歉，我们找不到您要查看的宠物信息</p>
        <router-link to="/adoption"
          class="inline-flex items-center text-orange-600 hover:text-orange-800 transition-colors duration-300">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24"
            stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          返回领养列表
        </router-link>
      </div>
    </div>
  </div>
  <fonnter />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAnimalStore } from '../stores/animalStore';
import fonnter from '../components/fonnter.vue';
import headd from '../components/head.vue';
import { Phone, Mail as MailIcon, MapPin } from 'lucide-vue-next';
import axios from 'axios';
import Cookies from 'js-cookie';

const route = useRoute();
const router = useRouter();
const animalStore = useAnimalStore();

const dogId = route.params.id;
const dog = computed(() => animalStore.getDogById(dogId));

// 领养须知
const adoptionRequirements = [
  {
    title: '居住环境',
    description: '需要有适合宠物生活的稳定居所'
  },
  {
    title: '时间保证',
    description: '能够保证每天有足够时间陪伴和照顾宠物'
  },
  {
    title: '经济能力',
    description: '具备承担宠物日常开销的经济能力'
  },
  {
    title: '接受回访',
    description: '同意定期回访，确保宠物生活状况'
  }
];

// 联系方式
const contactInfo = [
  {
    label: '电话咨询',
    value: '123-456-7890',
    icon: Phone,
    link: 'tel:123-456-7890'
  },
  {
    label: '邮件联系',
    value: 'contact@example.com',
    icon: MailIcon,
    link: 'mailto:contact@example.com'
  },
  {
    label: '地址',
    value: '上海市浦东新区XX路XX号',
    icon: MapPin,
    link: '#'
  }
];
const Avatar = (ref('')); //头像变量
const Nickname = (ref('')); //用户昵称
// 评论功能
const newComment = ref('');
const comments = ref([]);

const submitComment = async () => {
  if (!newComment.value.trim()) return;
  const token = Cookies.get('token');
  if (!token) {
    throw new Error('请先登录');
  }
  const jsonData = {
    blogId: Number(dogId),
    comment: newComment.value,
  };
  try {
    const response = await axios.post('http://localhost:8080/Petrescue/blog/addComment', jsonData,
      {
        headers: {
          'Content-Type': 'application/json'
          // 'Authorization': `Bearer ${Cookies.get('token')}` // 添加token
        },
        withCredentials: true
      }
    );
    const { code, data, message } = response.data;
    if (code == 200) {
    } else {
      alert(message);
    }

    // 获取当前时间并格式化为 ISO 8601 格式
    const currentTime = new Date().toISOString().replace(/\.\d{3}Z$/, '');

    // 更新本地评论列表
    comments.value.unshift({
      id: response.data.id,
      cuserName: Nickname,
      cuserAvatar: Avatar.value,
      comment: newComment.value,
      ctime: currentTime, // 使用 ISO 8601 格式的时间
      likes: 0,
      isLiked: false
    });

    newComment.value = '';
  } catch (error) {
    console.error('Error adding comment:', error);
  }
};

const likeComment = (comment) => {
  comment.isLiked = !comment.isLiked;
  comment.likes += comment.isLiked ? 1 : -1;
};

const replyToComment = (comment) => {
  newComment.value = `@${comment.username} `;
};

// 标签样式
const tagColors = [
  'bg-orange-100 text-orange-800',
  'bg-amber-100 text-amber-800',
  'bg-yellow-100 text-yellow-800',
  'bg-lime-100 text-lime-800',
  'bg-emerald-100 text-emerald-800'
];

const getTagStyle = (index) => {
  return tagColors[index % tagColors.length];
};
const storedUser = sessionStorage.getItem('user');
if (storedUser) {
  const { avatar, nickname } = JSON.parse(storedUser);
  Avatar.value = avatar;
  Nickname.value = nickname;
}
const read = ref();

onMounted(async () => {
  try {
    const response = await axios.post("http://localhost:8080/Petrescue/blog/Comments",
      { blogId: Number(dogId) },
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${Cookies.get('token')}` // 添加token
        },
        withCredentials: true
      }
    );
    const { data, message } = response.data;
    if (response.status === 200) {
      comments.value = data.commentList.map(comment => ({
        id: comment.id,
        cuserName: comment.cuserName,
        ctime: comment.ctime,
        comment: comment.comment,
        cuserAvatar: comment.cuserAvatar || 'http://example.com/default-avatar.jpg', // 设置默认头像
        likes: comment.likes || 0,
        isLiked: comment.isLiked || false
      }));
      const res = await axios.post('http://localhost:8080/Petrescue/blog/read', {
        blogId: Number(dogId)
      },
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${Cookies.get('token')}` // 添加token
          },
          withCredentials: true
        }
      );
      const { code, message } = res.data;
      if (code == 200) {
        // 如果需要，可以在这里更新本地的阅读数
        dog.readed = res.data.result;
      } else {
        alert(message);
      }
    } else {
      alert(message);
    }
  } catch (error) {
    console.error('Error fetching comments:', error);
  }
});
</script>

<style scoped lang="less">
.detail-container {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  min-height: 100vh;
  padding: 20px 0;
}

/* 基础动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 评论动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fadeIn 0.5s ease-out forwards;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #fef3c7;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #ea580c;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #c2410c;
}

.prose h2 {
  color: #7c2d12;
}

.prose p {
  color: #9a3412;
}

/* 输入框样式 */
textarea {
  transition: all 0.3s ease;
  color: #7c2d12;
  box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.1);

  &:focus {
    outline: none;
    background-color: rgba(254, 243, 199, 0.9);
    border-color: #c2410c;
    box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.3),
      inset 0 1px 3px rgba(251, 191, 36, 0.3);
  }

  &::placeholder {
    color: #d97706;
    opacity: 0.7;
  }
}
</style>